package com.mdp.tpa.wechat.wxpub.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import com.mdp.meta.client.service.ItemService;
import com.mdp.tpa.wechat.entity.AccessToken;
import com.mdp.tpa.wechat.pub.client.service.ArcClientService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mdp.core.utils.XmlUtils;
import com.mdp.tpa.wechat.api.AccessTokenService;
import com.mdp.tpa.wechat.api.CardEventService;
import com.mdp.tpa.wechat.api.MessageReplyService;
import com.mdp.tpa.wechat.api.MessageSendService;
import com.mdp.tpa.wechat.api.SecurityService;
import com.mdp.tpa.wechat.api.SubscribeEventService;

@Service
public class WxNotifyService{
	
	Log log=LogFactory.getLog(WxNotifyService.class);
	
	@Autowired(required = false)
	CardEventService wxApiCardEvent;
	
	@Autowired
	SubscribeEventService wxApiSubscribeEvent;
	@Autowired
	AccessTokenService accessTokenService;
	

	@Autowired
	ArcClientService arcClientService;

	/**
	 * 消息投放
	 */
	@Autowired
	MessageSendService msgSend;
	
	/**
	 * 从模板获取需要发给微信服务器的消息体
	 */
	@Autowired
	MessageReplyService msgReply;

	@Autowired
	ItemService itemService;
	
	
	@Autowired
	SecurityService security;

	public String getMsgForReplyToWeiXin( String msgFromWeiXin){
		String result="";
		try {
 			Map<String,Object> m=XmlUtils.string2Map(msgFromWeiXin);
			String msgType=(String) m.get("MsgType"); 
			String fromUserName=(String) m.get("FromUserName");
			String toUserName=(String) m.get("ToUserName");
			String createTime=(String) m.get("CreateTime");
			//事件推送
			if(m.containsKey("Event")){
				String event=(String) m.get("Event");
				String eventKey=(String) m.get("EventKey");
				//如果是关注事件
				if("event".equalsIgnoreCase(msgType) && event.contains("subscribe")){
					wxApiSubscribeEvent.doEvent(  event, msgType, fromUserName, toUserName, createTime, m);
 						AccessToken accessToken=accessTokenService.getAccessToken( );
						Date d=new Date(); 
						List<Map<String, Object>> items=new ArrayList<>();
						items=arcClientService.getNewList( "VT1001_TODAY_NEWS");
						String baseDomainUrl=itemService.getSysParam("baseDomain", "https://www.qingqinkj.com");
						if(items!=null && items.size()>0) {
							for (Map<String, Object> map : items) {
								map.put("url", baseDomainUrl+"/api/m1/arc/arc/archive/showArchive?id="+map.get("id"));
							}
							result=msgReply.news( fromUserName, toUserName, (int) d.getTime(), items);
						}else {
  							result=msgReply.text( fromUserName,toUserName, Integer.parseInt(createTime), null);
						} 
				
				}//如果扫描二维码进入并且已经关注
				else if("event".equalsIgnoreCase(msgType) && event.contains("SCAN")) {

					String ticket=(String) m.get("Ticket");

					Date d=new Date(); 
					List<Map<String, Object>> items=new ArrayList<>();
					items=arcClientService.getNewList( "VT1001_TODAY_NEWS");
					String baseDomainUrl=itemService.getSysParam("baseDomain", "https://www.qingqinkj.com");
					if(items!=null && items.size()>0) {
						for (Map<String, Object> map : items) {
							map.put("url", baseDomainUrl+"/api/m1/arc/arc/archive/showArchive?id="+map.get("id"));
						}
						result=msgReply.news( fromUserName, toUserName, (int) d.getTime(), items);
					}else {
						result=msgReply.text( fromUserName,toUserName , Integer.parseInt(createTime), null);
					} 
			
				}
				//如果是卡券事件，交由卡券系统处理
				else if("event".equalsIgnoreCase(msgType) && event.contains("card")){
					wxApiCardEvent.doEvent( event, msgType, fromUserName, toUserName, createTime, m);
				}else if("event".equalsIgnoreCase(msgType) && event.contains("MASSSENDJOBFINISH")){
					//群发事件、也写在卡券里面
					wxApiCardEvent.doEvent( event, msgType, fromUserName, toUserName, createTime, m);
				}else if("event".equalsIgnoreCase(msgType) && event.contains("CLICK")){
					if("VT1001_TODAY_RECOMMEND".equals(eventKey)){//今日推荐
						AccessToken accessToken=accessTokenService.getAccessToken( );
						Date d=new Date();
						List<Map<String, Object>> items=new ArrayList<>();
						items=arcClientService.getNewList(  eventKey);
						String baseDomainUrl=itemService.getSysParam("baseDomain", "https://www.qingqinkj.com");
						if(items!=null && items.size()>0) {
							for (Map<String, Object> map : items) {
								map.put("url", baseDomainUrl+"/api/m1/arc/arc/archive/showArchive?id="+map.get("id"));
							}
							result=msgReply.news( fromUserName, toUserName, (int) d.getTime(), items);
						}else {
							result=msgReply.text( fromUserName,toUserName , Integer.parseInt(createTime), null);
						}
					}else if("VT1001_TODAY_NEWS".equals(eventKey)){
						AccessToken accessToken=accessTokenService.getAccessToken( );
						Date d=new Date();
						List<Map<String, Object>> items=new ArrayList<>();
						items=arcClientService.getNewList( eventKey);
						String baseDomainUrl=itemService.getSysParam("baseDomain", "https://www.qingqinkj.com");
						if(items!=null && items.size()>0) {
							for (Map<String, Object> map : items) {
								map.put("url", baseDomainUrl+"/api/m1/arc/arc/archive/showArchive?id="+map.get("id"));
							}
							result=msgReply.news( fromUserName, toUserName, (int) d.getTime(), items);
						}else {
							result=msgReply.text( fromUserName,toUserName, Integer.parseInt(createTime), null);
						}
					}
				}
			}
			//普通文本信息
			else if(m.containsKey("Content")){
				String content=(String) m.get("Content");
				AccessToken accessToken=accessTokenService.getAccessToken( );
				result=msgReply.text( fromUserName, toUserName, Integer.parseInt(createTime), content);
			}
		} catch (Exception e) {
			log.error("",e);
		}
		return result;
		
	}
	// 将request中的参数转换成Map
    public Map<String, String> convertRequestParamsToMap(HttpServletRequest request) {
        Map<String, String> retMap = new HashMap<String, String>();

        Set<Entry<String, String[]>> entrySet =request.getParameterMap().entrySet();

        for (Entry<String, String[]> entry : entrySet) {
            String name = entry.getKey();
            String[] values = entry.getValue();
            int valLen = values.length;

            if (valLen == 1) {
                retMap.put(name, values[0]);
            } else if (valLen > 1) {
                StringBuilder sb = new StringBuilder();
                for (String val : values) {
                    sb.append(",").append(val);
                }
                retMap.put(name, sb.toString().substring(1));
            } else {
                retMap.put(name, "");
            }
        }

        return retMap;
    }
	
}
